<template>
  <div class="container with-nav-padding">
    <search-input :status="2"></search-input>
    <div class="mall-slider">
      <yd-slider
        autoplay="3000"
        pagination-color="rgba(255,255,255,0.4)"
        pagination-activecolor="rgba(255,255,255,0.8)"
      >
        <yd-slider-item v-for="(item, index) in carouselList" :key="index">
          <div @click="linkHref(item.link)">
            <img style="width:100%" :src="item.image" />
          </div>
        </yd-slider-item>
      </yd-slider>
    </div>
    <main-nav :type="'dynamic'" @filterDynamics="filterDynamics"></main-nav>
    <yd-slider :show-pagination="false" autoplay="3000">
      <yd-slider-item v-for="item in noticeList" :key="item.id" v-if="item.title">
        <div
          @click="
            $router.push({
              path: '/notice-detail',
              query: {
                id: item.id
              }
            })
          "
          @movetouch.stop
          class="news"
        >
          {{ item.title }}
          <!-- <img
            class="news-icon"
            src="@/assets/车主宝首页改-assets/返回.png"
            alt=""
          />-->
        </div>
      </yd-slider-item>
    </yd-slider>
    <div class="dynamics-panel">
      <div :class="{ 'tab-fixed': tabFixed }">
        <div :class="{ 'panel-nav': true, 'with-grey-bottom-border': true }">
          <div class="item-box" ref="navItem">
            <div
              v-for="(item, index) in itemList"
              :key="index"
              @click="tabClick(item.id)"
              :class="{ 'nav-item': true, active: currentItem == item.id }"
              v-if="!(item.id === 1 || item.id === 3)"
            >
              <span
                :class="{
                  'item-span': true,
                  'span-active': currentItem == item.id
                }"
                :style="{borderBottomColor: mainColor}"
              >{{ item.dynamic_name }}</span>
            </div>
          </div>
          <div
            @touchstart="handleTouchStart"
            @touchend="handleTouchEnd"
            @touchmove.prevent
            class="item-box dynamic-nav"
          >
            <div class="animate" :style="{ transform: 'translate(-' + translate + '%,0)' }"></div>
          </div>
          <div class="hidden"></div>
        </div>
      </div>
    </div>

    <div :style="{ paddingTop: tabFixed ? 1.6 + 'rem' : 0 }">
      <dynamic-panel-1 v-if="dynamicStatus === 1 && dynamicList.length"></dynamic-panel-1>
      <div class="no-dynamic" v-if="!dynamicList.length && carouselList.length">暂无视频</div>
    </div>
    <div v-if="showAtten" class="recommend-panel">
      <div class="top-title" v-show="titleStatus" :style="{background: mainColor}">
        <div class="text">你还没有关注的人哦</div>
        <div class="sub-text">已经关注了?别着急,他们最近没更新呢</div>
      </div>
      <div class="recommend-list">
        <!-- <div class="title">
          <div class="text">可能感兴趣的人</div>
          <div class="btn">换一批</div>
        </div>-->
        <div
          v-for="(item, index) in recommends"
          :key="index"
          class="recommend-cell with-grey-bottom-border"
        >
          <img :src="item.avatar" alt />
          <div class="info">
            <div class="username">{{ item.username }}</div>
            <div class="follower">粉丝{{ item.fans }}</div>
            <div class="signature">{{ item.signature }}</div>
          </div>
          <button class="follow-btn" @click="attention(item.id, $event)">
            <!-- <img src="@/assets/车主宝首页改-assets/fu.png" alt=""/> -->
            +关注
          </button>
        </div>
      </div>
    </div>
    <div
      v-if="dynamicsAuth"
      class="fixed-btn"
      @click="showRelease = true"
      :style="{backgroundColor: mainColor}"
    >发布</div>
    <release-mask v-if="showRelease" @panelClose="showRelease = false"></release-mask>
    <loadMore @loadMore="loadMore"></loadMore>
  </div>
</template>

<script>
import searchInput from "@/components/search/search-input.vue";
import dynamicPanel1 from "./component/dynamic-panel-1.vue";
import dynamicPanel2 from "./component/dynamic-panel-2.vue";
import releaseMask from "./component/release-mask.vue";
import mainNav from "@/components/main-nav.vue";
import loadMore from "@/components/load-more";
import {
  getDtData,
  follow,
  getIndex,
  getRecommend,
  getArticle
} from "@/api/dynamics";
import { mapState } from "vuex";
import { getProfileInfo } from "@/api/profile";
import { getToken } from "@/utils/utils";
export default {
  data() {
    return {
      itemList: [],
      touchPosition: 0,
      translate: 0,
      currentItem: 2,
      dynamicList: [],
      showRelease: false,
      tabScrollTop: null,
      showAtten: false,
      recommends: [],
      page: 1,
      isAll: false,
      loading: false,
      titleStatus: false,
      tabFixed: false,
      dynamicStatus: 1,
      noticeList: [],
      carouselList: [],
      dynamicsAuth: true
    };
  },
  computed: {
    ...mapState({
      token: state => state.user.token,
      mainColor: state => state.app.mainColor
    })
  },
  watch: {
    currentItem() {
      this.dynamicList = []; //每次点击将动态列清空，之后判断当前的位置，重新赋值
      this.page = 1;
    }
  },
  methods: {
    linkHref(link) {
      window.location.href = link;
    },
    handleScroll() {
      let scrollTop =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop;
      this.tabFixed = scrollTop >= this.tabScrollTop + 475 ? true : false;
    },
    handleTouchStart(event) {
      this.touchPosition = event.touches[0].clientX;
    },
    handleTouchEnd(event) {
      if (
        event.changedTouches[0].clientX - this.touchPosition < -80 &&
        this.translate + 50 <= 25 * this.itemList.length - 125
      ) {
        this.translate += 50;
      } else if (
        event.changedTouches[0].clientX - this.touchPosition < -80 &&
        this.translate + 50 > 25 * this.itemList.length - 125
      ) {
        this.translate = 25 * this.itemList.length - 125;
      } else if (
        event.changedTouches[0].clientX - this.touchPosition > 80 &&
        this.translate - 50 >= 0
      ) {
        this.translate -= 50;
      } else if (
        event.changedTouches[0].clientX - this.touchPosition > 80 &&
        this.translate - 50 < 0
      ) {
        this.translate = 0;
      } else if (
        event.changedTouches[0].clientX - this.touchPosition < -40 &&
        this.translate < 25 * this.itemList.length - 125
      ) {
        this.translate += 25;
      } else if (
        event.changedTouches[0].clientX - this.touchPosition > 40 &&
        this.translate !== 0
      ) {
        this.translate -= 25;
      }
      this.touchPosition = 0;
    },
    attention(userId, e) {
      //点击关注触发函数
      follow({
        user: userId
      }).then(res => {
        //关注成功
        if (res.data.data.type == 1) e.target.innerText = "取消关注";
        //取消关注成功
        if (res.data.data.type == 2) e.target.innerHTML = "+关注";
      });
    },
    tabClick(id) {
      this.currentItem = id;
      this.dynamicList = [];
      this.page = 1;
      if (id !== 2) {
        getDtData({
          classifyId: id,
          page: this.page
        }).then(res => {
          if (res.status === 200) {
            if (id == 1) {
              //关注
              this.dynamicStatus = 0;
              if (res.status === 200 && res.data.data.concerns_count == 0) {
                //没有关注的人
                this.titleStatus = true;
                //获取推荐用户
                getRecommend({
                  page: 1
                }).then(res => {
                  if (page === 1) this.recommends = [];
                  this.recommends.push(...res.data.data);
                });
                //显示推荐用户模板
                this.showAtten = true;
              } else {
                //有关注的人
                this.titleStatus = false;
                this.dynamicList.push(...res.data.data.concerns);
                //推荐关注
                getRecommend().then(res => {
                  this.recommends.push(...res.data.data);
                });
                this.showAtten = true;
                this.dynamicStatus = 1;
              }
            } else if (id !== 1 && id !== 3) {
              //发现
              this.showAtten = false; //隐藏关注组件
              this.dynamicStatus = 1; //显示动态组件
              this.dynamicList.push(...res.data.data);
            } else if (id == 3) {
              //附近
              this.showAtten = false;
              this.dynamicStatus = 1; //显示动态组件
              this.dynamicList.push(...res.data.data);
            }
          }
        })
      } else {
        this.defaultMount(this.page)
      }
    },
    getNav() {
      //获取到默认的导航项
      getIndex().then(res => {
        this.carouselList = res.data.data.carousel;
        this.itemList = res.data.data.classify.classify_default.concat(
          res.data.data.classify.classify
        );
        this.noticeList = res.data.data.notice;
        //获取用户动态权限信息
      });
    },
    //页面刷新时默认渲染发现的全部动态数据
    defaultMount(page) {
      getDtData({
        classifyId: 2,
        page
      }).then(res => {
        if (res.status === 200) {
          getArticle({ page: this.page }).then(res1 => {
            if (res1.status === 200) {
              let arr = res.data.data;
              let articleList = res1.data.data.map(item => {
                item.type = "article";
                return item;
              });
              articleList.forEach(value =>
                arr.splice(Math.random() * arr.length, 0, value)
              );
              this.showAtten = false; //隐藏关注页
              this.dynamicStatus = 1; //显示动态页
              this.dynamicList.push(...arr); //将请求到的动态数据挂载到数据层
              if (res.data.data.length === 0) {
                this.isAll = true;
                this.$dialog.toast({
                  mes: "已经到最底了",
                  timeout: 1000
                });
              }
            }
          });
        }
      });
    },
    //加载更多
    loadMore() {
      if (this.loading || this.isAll || this.dynamicList.length === 0) return;
      this.loading = true;
      this.defaultMount(++this.page);
    },
    filterDynamics(val) {
      console.log(val);
      this.tabClick(val);
      // this.dynamicList = [];
      // this.page = 1;
      // getDtData({
      //   classifyId: val,
      //   page: 1
      // }).then(res => {
      //   if (res.status === 200) {
      //     getArticle({ page: this.page, classifyId: val }).then(res1 => {
      //       if (res1.status === 200) {
      //         let arr = res.data.data;
      //         let articleList = res1.data.data.map(item => {
      //           item.type = "article";
      //           return item;
      //         });
      //         articleList.forEach(value =>
      //           arr.splice(Math.random() * arr.length, 0, value)
      //         );
      //         this.showAtten = false; //隐藏关注页
      //         this.dynamicStatus = 1; //显示动态页
      //         this.dynamicList.push(...arr); //将请求到的动态数据挂载到数据层
      //         if (res.data.data.length === 0) {
      //           this.isAll = true;
      //           this.$dialog.toast({
      //             mes: "已经到最底了",
      //             timeout: 1000
      //           });
      //         }
      //       }
      //     });
      //   }
      // });
    }
  },
  mounted() {
    this.tabScrollTop = document.getElementsByClassName(
      "panel-nav"
    )[0].offsetTop;
    window.addEventListener("scroll", this.handleScroll, true);
  },
  activated() {
    if (this.$route.params.action === "read") {
      this.filterDynamics(11);
    }
    // if (getToken()) {
    //   getProfileInfo().then(res => {
    //     if (res.status === 200) {
    //       this.dynamicsAuth = [149, 151].includes(res.data.data.id);
    //     }
    //   });
    // }
  },
  created() {
    this.getNav();
    this.defaultMount(1);
  },
  components: {
    searchInput,
    dynamicPanel1,
    dynamicPanel2,
    releaseMask,
    mainNav,
    loadMore
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  }
};
</script>

<style lang="less" scoped>
.container {
  .mall-slider {
    background: #fff;
    padding: 0 3.2%;
  }
  .news {
    height: 1.76rem;
    background: #fff;
    margin: 0.48rem 0;
    font-size: 0.6rem;
    color: #444444;
    line-height: 1.76rem;
    padding: 0 3.2%;
    font-weight: bold;
    position: relative;

    .news-icon {
      position: absolute;
      right: 3.2%;
      height: 0.6rem;
      top: calc(50% - 0.3rem);
    }
  }

  .dynamics-panel {
    .panel-nav {
      background: #fff;
      height: 1.76rem;
      line-height: 1.76rem;
      position: relative;

      .static-nav {
        position: absolute;
        left: 0;
      }
      .hidden {
        position: absolute;
        left: 0;
        bottom: -0.1rem;
        width: 100%;
        height: 0.1rem;
        background: #fff;
      }
      .item-box {
        white-space: nowrap;
        overflow-x: auto;
        text-align: center;

        .animate {
          transition-duration: 0.2s;
        }

        .nav-item {
          display: inline-block;
          font-size: 0.64rem;
          font-family: "SimHei";
          width: 25%;
          transition-duration: 0.2s;
          text-align: center;
          color: #444444;
        }

        .item-span {
          border-bottom: 0px solid #0078ff;
          transition-duration: 0.15s;
        }

        .span-active {
          border-bottom: 0.24rem solid #0078ff;
        }

        .active {
          font-size: 0.7rem;
          font-weight: bold;
        }
      }

      .dynamic-nav {
        position: absolute;
        left: 45%;
        top: 0;
        .nav-item {
          width: 25%;
        }
      }
    }
  }

  .panel-filter {
    height: 1.64rem;
    background: #fff;
    padding: 0.3rem 3.2%;

    .filter {
      height: 1rem;
      font-size: 0.48rem;
      line-height: 1rem;
      color: #444444;
      background: rgba(245, 245, 245, 1);
      padding: 0 0.48rem;
      margin-right: 0.24rem;
      border-radius: 0.5rem;
      display: inline-block;
    }

    .active {
      background: rgba(51, 147, 255, 0.2);
    }
  }

  .recommend-panel {
    padding: 0.48rem;
    background: #fff;

    .top-title {
      height: 4rem;
      background: rgba(0, 120, 255, 1);
      padding-left: 0.92rem;
      padding-top: 1rem;

      .text {
        font-weight: bold;
        color: rgba(255, 255, 255, 1);
        font-size: 0.64rem;
      }

      .sub-text {
        color: rgba(255, 255, 255, 0.75);
        font-size: 0.56rem;
        margin-top: 0.1rem;
      }
    }

    .recommend-list {
      padding-bottom: 3rem;

      .title {
        display: flex;
        justify-content: space-between;
        margin: 0.4rem 0;

        .text {
          color: rgba(51, 51, 51, 1);
          font-weight: bold;
          font-size: 0.6rem;
          line-height: 1.16rem;
        }

        .btn {
          background: rgba(37, 119, 227, 0.1);
          border-radius: 0.24rem;
          height: 1.16rem;
          line-height: 1.16rem;
          color: rgba(37, 119, 227, 1);
          font-size: 0.48rem;
          padding: 0 0.34rem;
        }
      }

      .recommend-cell {
        display: flex;
        margin: 0.76rem 0 0;
        padding-bottom: 0.76rem;
        position: relative;

        .follow-btn {
          position: absolute;
          right: 0;
          top: 0.3rem;
          border: none;
          background: rgba(0, 120, 255, 1);
          color: #fff;
          height: 1rem;
          line-height: 1rem;
          font-size: 0.48rem;
          padding: 0 0.4rem;
          border-radius: 0.5rem;

          img {
            height: 0.48rem;
            width: 0.48rem;
            vertical-align: middle;
            margin: 0;
          }
        }

        img {
          width: 1.36rem;
          height: 1.36rem;
          margin-top: 0.3rem;
        }

        .info {
          margin-left: 0.4rem;

          .username {
            font-weight: bold;
            color: rgba(68, 68, 68, 1);
            font-size: 0.56rem;
          }

          .follower {
            color: rgba(153, 153, 153, 1);
            font-size: 0.48rem;
            margin: 0.24rem 0;
          }

          .signature {
            color: rgba(102, 102, 102, 1);
            font-size: 0.48rem;
          }
        }
      }
    }
  }

  .fixed-btn {
    position: fixed;
    right: 3.4%;
    bottom: 4rem;
    height: 2rem;
    width: 2rem;
    border-radius: 50%;
    font-size: 0.52rem;
    color: #fff;
    background-image: url("../../assets/车主宝首页改-assets/fu.png");
    background-size: 0.55rem 0.55rem;
    background-position: 50% 30%;
    background-color: #0078ff;
    background-repeat: no-repeat;
    text-align: center;
    padding-top: 1.1rem;
    z-index: 99;
  }

  .tab-fixed {
    position: fixed !important;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 999;
  }
}
.no-dynamic {
  text-align: center;
  font-size: 0.5rem;
  line-height: 8rem;
}
</style>
